import time

import uiautomator2 as u2
from uiautomator2 import ConnectError

from le_engine.image_matcher import ImageMatcher
from utils.logger import log
from le_engine.config import CommonConfig, IconName
from utils.utils import CommonUtils


class LittleEmpire:
    package_name = CommonConfig.package_name
    main_activity = ".MainActivity"

    def __init__(self, ip, port, username=None, psw=None):

        self.ip = ip
        self.port = port

        self.username = username
        self.psw = psw
        self.pk = CommonUtils.get_pk(self.ip, self.port, self.username)

        try:
            self.client = u2.connect(f"{self.ip}:{self.port}")
        except ConnectError:
            self.error_exit(f"安卓设备 {self.ip}:{self.port} 不在线！你的模拟器启动了吗？你就要 刷")
        except Exception as e:
            self.error_exit(f"安卓设备链接异常: {e}")
        else:
            self.im = ImageMatcher(self.client, pk=self.pk)

    def get_client(self):
        return self.client

    def close_current_page(self):
        self.client.click(*CommonConfig.close_position)

    def enter_email(self):
        # 进入邮箱
        self.client.click(*CommonConfig.email_position)

    def enter_train(self):
        # 进入训练场
        self.client.click(*CommonConfig.train_position)
        if self.client(text="训练场").wait(CommonConfig.e_t_o):
            log.info("成功进入训练场", extra={"pk": self.pk})
            return True
        else:
            log.error("进入训练场失败", extra={"pk": self.pk})
            return False

    def enter_a_report(self):
        # 进入战报页面
        if not self.client(text='信件').wait(timeout=1):
            self.enter_email()
            if not self.client(text='信件').wait(timeout=1):
                self.inter_game()
                self.enter_email()
        self.client.click(*CommonConfig.attack_report_position)

    def error_exit(self, msg=None, forever=False):
        log.error(msg)
        log.error(f"老哥，{'出错了哦' if msg is None else msg}，退出游戏！", extra={"pk": self.pk})
        # self.client.app_stop(self.package_name)
        if not forever:
            exit()

    def success_exit(self, msg=None):
        log.info("搞定，退出游戏！" if msg is None else msg, extra={"pk": self.pk})
        self.client.app_stop(self.package_name)
        exit()

    def inter_game(self, forever=False):
        log.info("正在打开游戏...", extra={"pk": self.pk})
        self.client.app_stop(self.package_name)
        self.client.app_start(self.package_name, self.main_activity)

        if self.username and self.psw and self.client(text="账号").click_exists(timeout=CommonConfig.net_t_o + 5):
            log.info(f"输入用户名:{self.username}", extra={"pk": self.pk})
            self.client(resourceId="com.camelgames.hogwarts:id/login_text").clear_text()
            self.client(resourceId="com.camelgames.hogwarts:id/login_text").click()
            self.client(resourceId="com.camelgames.hogwarts:id/login_text").send_keys(self.username)

            log.info(f"输入密码", extra={"pk": self.pk})
            self.client(resourceId="com.camelgames.hogwarts:id/pwd_text").clear_text()
            self.client(resourceId="com.camelgames.hogwarts:id/pwd_text").click()
            self.client(resourceId="com.camelgames.hogwarts:id/pwd_text").send_keys(self.psw)

            log.info(f"登录", extra={"pk": self.pk})
            self.client(text="登录").click()

            if self.client(text="君主名密码不匹配").wait(timeout=CommonConfig.net_t_o):
                self.success_exit("君主名密码不匹配")
        else:
            log.info(f"直接点击开始游戏", extra={"pk": self.pk})
            self.client(text="开始游戏").click_exists(timeout=CommonConfig.net_t_o)

        if self.im.find_image(CommonConfig.img_path(IconName.main_castle), max_retries=5):
            log.info("成功进入游戏", extra={"pk": self.pk})
            return True
        elif self.im.find_image(CommonConfig.img_path(IconName.sos), max_retries=5):
            log.info("老哥你好像被人打了， 成功进入游戏", extra={"pk": self.pk})
            return True
        self.error_exit(msg="进入游戏失败", forever=forever)
        return False

    def find_space_gate(self):
        # 寻找时空门
        config = CommonConfig.cage_config.get(self.username, CommonConfig.cage_config["common"])

        swap_list = config.get("space_gate_list", [])
        for swap in swap_list:
            self.client.swipe(*swap, duration=0.5)

        # if self.im.click_image(CommonConfig.img_path(IconName.space_gate), max_retries=3) or self.im.click_image(CommonConfig.img_path(IconName.space_gate_1), max_retries=3):
        #     return True

        self.client.click(0.546, 0.355)
        return True

    def enter_aux_castle(self):
        # 进入附城
        if self.find_space_gate():
            if self.im.click_image(CommonConfig.img_path(IconName.space_gate_tran)):
                return True

        return False

    @property
    def cage_position(self):
        config = CommonConfig.cage_config.get(self.username, CommonConfig.cage_config["common"])
        if config:
            return config['cage_position']
        else:
            return self.error_exit("缺少牢笼配置")

    @property
    def cage_swap_list(self):
        config = CommonConfig.cage_config.get(self.username, CommonConfig.cage_config["common"])
        if config:
            return config['cage_swap_list']
        else:
            return self.error_exit("缺少牢笼配置")

    @property
    def main_castle_swap_list(self):
        config = CommonConfig.cage_config.get(self.username, CommonConfig.cage_config["common"])
        if config:
            return config['main_castle']
        else:
            return self.error_exit("缺少寻找主城堡配置")

    def find_cage(self):
        # 滑动屏幕，找到牢笼
        for item in self.cage_swap_list:
            self.client.swipe(*item, duration=0.5)

    def find_main_castle(self):
        time.sleep(2)
        # 滑动屏幕，找到牢笼
        for item in self.main_castle_swap_list:
            self.client.swipe(*item, duration=0.5)
